package com.prawn.monitor.service;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.prawn.monitor.dao.WaterDataDao;
import com.prawn.monitor.pojo.WaterData;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class WaterDataService {

	@Autowired
	private WaterDataDao waterDataDao;
	
	@Autowired
	private IdWorker idWorker;

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<WaterData> findAll() {
		return waterDataDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<WaterData> findSearch(Map whereMap, int page, int size) {
		Specification<WaterData> specification = createSpecification(whereMap);
		Sort sort=new Sort(Sort.Direction.ASC, "acquisitionTime");
		PageRequest pageRequest =  PageRequest.of(page-1, size,sort);
		return waterDataDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<WaterData> findSearch(Map whereMap) {
		Specification<WaterData> specification = createSpecification(whereMap);
		Sort sort=new Sort(Sort.Direction.ASC,"acquisitionTime");
		return waterDataDao.findAll(specification,sort);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public WaterData findById(String id) {
		return waterDataDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param waterData
	 */
	public void add(WaterData waterData) {
		waterData.setId( idWorker.nextId()+"" );
		waterDataDao.save(waterData);
	}

	/**
	 * 修改
	 * @param waterData
	 */
	public void update(WaterData waterData) {
		waterDataDao.save(waterData);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
		waterDataDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<WaterData> createSpecification(Map searchMap) {

		return new Specification<WaterData>() {

			@Override
			public Predicate toPredicate(Root<WaterData> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // id
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.equal(root.get("id").as(String.class), (String)searchMap.get("id")));
                }
				// 所属基地id
				if (searchMap.get("baseId") != null && !"".equals(searchMap.get("baseId"))) {
					predicateList.add(cb.equal(root.get("baseId").as(String.class),  (String) searchMap.get("baseId") ));
				}
                // 水质设备编号
                if (searchMap.get("equipmentId")!=null && !"".equals(searchMap.get("equipmentId"))) {
                	predicateList.add(cb.equal(root.get("equipmentId").as(String.class), (String)searchMap.get("equipmentId")));
                }
                // 压力传感器状态（0）：关（1）：开
                if (searchMap.get("pressureSensor status")!=null && !"".equals(searchMap.get("pressureSensor status"))) {
                	predicateList.add(cb.equal(root.get("pressureSensor status").as(String.class), (String)searchMap.get("pressureSensor status")));
                }
                // 浮球阀状态（0）：关（1）：开
                if (searchMap.get("floatValveStatus")!=null && !"".equals(searchMap.get("floatValveStatus"))) {
                	predicateList.add(cb.equal(root.get("floatValveStatus").as(String.class), (String)searchMap.get("floatValveStatus")));
                }
                // 水质传感器工作状态0（关闭）1（工作中）2（故障）
                if (searchMap.get("waterQualityWorking")!=null && !"".equals(searchMap.get("waterQualityWorking"))) {
                	predicateList.add(cb.equal(root.get("waterQualityWorking").as(String.class), (String)searchMap.get("waterQualityWorking")));
                }
				// 日期
				if (searchMap.get("startTime") != null && !"".equals(searchMap.get("startTime"))) {
					try {
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						predicateList.add(cb.greaterThanOrEqualTo(root.get("acquisitionTime").as(Date.class), dateFormat.parse((String) searchMap.get("startTime"))));

						if (searchMap.get("endTime") != null && !"".equals(searchMap.get("endTime"))) {
							predicateList.add(cb.lessThanOrEqualTo(root.get("acquisitionTime").as(Date.class), dateFormat.parse((String) searchMap.get("endTime"))));
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
                // 备用字段1
                if (searchMap.get("spare1")!=null && !"".equals(searchMap.get("spare1"))) {
                	predicateList.add(cb.equal(root.get("spare1").as(String.class), (String)searchMap.get("spare1")));
                }
                // 备用字段2
                if (searchMap.get("spare2")!=null && !"".equals(searchMap.get("spare2"))) {
                	predicateList.add(cb.equal(root.get("spare2").as(String.class), (String)searchMap.get("spare2")));
                }

//				// 日期
//				if (searchMap.get("startTime") != null && !"".equals(searchMap.get("startTime"))) {
//					try {
//						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//						predicateList.add(cb.greaterThanOrEqualTo(root.get("acquisitionTime").as(Date.class), dateFormat.parse((String) searchMap.get("startTime"))));
//
//						if (searchMap.get("endTime") != null && !"".equals(searchMap.get("endTime"))) {
//							predicateList.add(cb.lessThanOrEqualTo(root.get("acquisitionTime").as(Date.class), dateFormat.parse((String) searchMap.get("endTime"))));
//						}
//					} catch (ParseException e) {
//						e.printStackTrace();
//					}
//				}

				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

}
